package geektime.concurrent.part2.executors;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceDemo {

    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        // 2秒后执行任务，执行后不再重复执行
        executor.schedule(() -> {
            System.out.println(Thread.currentThread().getName() + " fixedRate " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 2, TimeUnit.SECONDS);

//        // 模拟每隔2秒执行一次任务
//        executor.scheduleAtFixedRate(() -> {
//            System.out.println(Thread.currentThread().getName() + " fixedRate " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
//            try {
//                TimeUnit.SECONDS.sleep(1);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }, 2, 2, TimeUnit.SECONDS);

        // 模拟每次任务执行完之后，间隔2秒再执行
//        executor.scheduleWithFixedDelay(() -> {
//            System.out.println(Thread.currentThread().getName() + " fixedDelay " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
//            try {
//                TimeUnit.SECONDS.sleep(1);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }, 2, 2, TimeUnit.SECONDS);

    }
}
